<script setup lang="ts">
import * as echarts from 'echarts'
import { ECharts, EChartsOption } from 'echarts'
import { EChartsUtil, getLineStyle } from '@utils/echarts'
import { Cell } from '@antv/x6'
import { FnOperationControl } from '@utils/object-util/periodic-execution/FnOperationControl'
import { DateFormat, moment, recentDate } from '@utils/moment'
import { getAlarmStatisticsBySceneId } from '@/api/alarm'
import { getVariableHistoryByDateAPI } from '@/api/history'
import { ObjectUtil } from '@utils/object-util'
const lineChartRef = shallowRef<HTMLDivElement>()
const lineChart = shallowRef<ECharts>()

const getNode = inject<{(): Cell }>('getNode')
const currentNode = getNode()
const dataConfig = currentNode.data.dataConfig
const { echartsOptions, echartsConfig } = dataConfig
onMounted(() => {
  initChart()
  currentNode.data.dataConfig.updateChart = (e) => {
    console.log(123)
  }
  lineChart.value.setOption({
    series: [{
      data: [
        // ['2020-12-12', 0],
        ['2020-12-10', 10],
        ['2020-12-11', 15],
        ['2020-12-12', 13],
        ['2020-12-13', 15],
        ['2020-12-14', 10]
        // ['2020-12-12', 0]
      ]
    }]
  } as EChartsOption)
})
onBeforeUnmount(() => {
  // clearInterval(test)
})

const runTypeDic = {
  historicalData: {
    run: historicalData,
    name: '历史数据'
  },
  liveDataToday: {
    run: liveDataToday,
    name: '今日实时数据'
  }
}

function run (data: any) {
  dataType = currentNode.data.dataConfig.dataOption.dataType
  if (dataType) {
    runTypeDic[dataType].run()
  } else {
    runEmpty()
  }
}

function runEmpty () {
  lineChart.value.setOption({
    yAxis: [{ name: '' }],
    xAxis: [{ data: [] }],
    series: [{ name: '--', data: [] }]
  } as EChartsOption)
}

// region TODO 折线图数据
let dataType = ''
let operationControl: FnOperationControl = null
const isLoading = ref(false)
// region TODO 历史数据
function historicalData () {
  const { deviceId, variableId } = currentNode.data.dataConfig
  const { dataRange } = currentNode.data.dataConfig.dataOption
  if (!variableId || !dataRange) return
  operationControl = new FnOperationControl({
    async fn (options) {
      if (options.isFirstRun) {
        isLoading.value = true
      }
      const [startTime, endTime] = recentDate(dataRange - 1)
      console.log(deviceId, variableId, startTime, endTime)
      return getVariableHistoryByDateAPI({
        tableName: deviceId,
        variableIds: [variableId],
        startTime,
        endTime
      }).then((res) => {
        res.result().then((rdata) => {
          rdata.data ??= []
          const data = rdata.data[0]?.variableVOList || []
          const seriesData = []
          const item0 = data[0] || {}
          const unit = item0.unit
          const name = item0.name
          for (let i = 0, len = data.length; i < len; i++) {
            const item = data[i]
            seriesData.push([item.ts, item.value])
          }
          lineChart.value.setOption({
            yAxis: [{ name: unit }],
            series: [{ name, data: seriesData }]
          } as EChartsOption)
        })
      }).finally(() => {
        isLoading.value = false
      })
    },
    rightRun: true,
    timeout: 1800000
  })
}
// endregion

// region TODO 今日实时数据
function liveDataToday () {
  const { deviceId, variableId } = currentNode.data.dataConfig
  // const { dataRange } = currentNode.data.dataConfig.dataOption
  if (!variableId) return
  const currentOptions = lineChart.value.getOption()
  console.log(currentOptions)
  // 双X轴
  const xAxis2Data = []
  for (let i = 0; i <= 24; i += 2) {
    xAxis2Data.push(i.toString().padStart(2, '0') + ':00')
  }
  const xAxis1 = currentOptions.xAxis[0]
  const xAxis2 = ObjectUtil.assignDeep(ObjectUtil.copy(xAxis1), { type: 'category', position: 'bottom', data: xAxis2Data, axisPointer: { show: false } })
  xAxis1.axisLabel.show = false
  lineChart.value.setOption({
    xAxis: [xAxis1, xAxis2]
  } as EChartsOption)
  operationControl = new FnOperationControl({
    async fn (options) {
      if (options.isFirstRun) {
        isLoading.value = true
      }
      const [startTime, endTime] = recentDate(7 - 1)
      console.log(deviceId, variableId, startTime, endTime)
      return getVariableHistoryByDateAPI({
        tableName: deviceId,
        variableIds: [variableId],
        startTime: moment().format(DateFormat.Date) + ' 00:00:00',
        endTime: moment().format(DateFormat.DateTime)
      }).then((res) => {
        res.result().then((rdata) => {
          rdata.data ??= []
          const data = rdata.data[0]?.variableVOList || []
          const seriesData = []
          const item0 = data[0] || {}
          const unit = item0.unit
          const name = item0.name
          for (let i = 0, len = data.length; i < len; i++) {
            const item = data[i]
            seriesData.push([item.ts, item.value])
          }
          const today = moment().format(DateFormat.Date)
          lineChart.value.setOption({
            yAxis: [{ name: unit }],
            xAxis: [{
              min: today + ' 00:00:00',
              max: today + ' 23:59:59'
            }],
            series: [{ name, data: seriesData }]
          } as EChartsOption)
        })
      }).finally(() => {
        isLoading.value = false
      })
    },
    rightRun: true,
    timeout: 300000
  })
}
// endregion

// endregion

// region TODO 更新ChartOptions
function updateChartAttrs (e) {
  dataConfig.echartsOptions = e
  lineChart.value.setOption(e)
}
// endregion

// region TODO 更新折线颜色
function updateChartColor (e) {
  updateChartAttrs(e)
  if (echartsConfig.area.show) updateChartArea()
}
// endregion

// region TODO 更新文本颜色
function updateChartText (e) {
  echartsConfig.textColor = e
  lineChart.value.setOption({
    legend: { textStyle: { color: e.color } },
    yAxis: [{
      nameTextStyle: { color: e.color },
      axisLabel: { color: e.color }
    }],
    xAxis: [{
      axisLabel: { color: e.color },
      axisLine: { lineStyle: { color: e.color } },
      axisTick: { lineStyle: { color: e.color } }
    }]
  } as EChartsOption)
}
// endregion

// region TODO 更新分割线颜色
function updateSplitLineColor (e) {
  echartsConfig.splitLine = e
  lineChart.value.setOption({
    yAxis: [{
      splitLine: {
        lineStyle: {
          color: [e.color]
        }
      }
    }]
  } as EChartsOption)
}
// endregion

// region TODO 更新渐变颜色
function updateChartArea (e?) {
  if (e) echartsConfig.area = e
  const { show, color } = echartsConfig.area
  if (show) {
    lineChart.value.setOption({
      series: [{
        areaStyle: {
          color: EChartsUtil.getLinearGradient(echartsOptions.series[0].itemStyle.color, color)
        }
      }]
    } as EChartsOption)
  } else {
    lineChart.value.setOption({
      series: [{ areaStyle: undefined }]
    })
  }
}
// endregion

// region TODO 初始化Chart
function initChart () {
  lineChart.value = echarts.init(lineChartRef.value)
  lineChart.value.setOption(getLineStyle({
    color: echartsOptions.series[0].itemStyle.color,
    unit: '单位',
    name: '名称',
    area: echartsConfig.area.show,
    areaColor: echartsConfig.area.color
  }).setLegend(echartsOptions.legend)
    .setTooltip(echartsOptions.tooltip)
    .getResult())
  lineChart.value.setOption({
    toolbox: echartsOptions.toolbox,
    legend: {
      textStyle: { color: echartsConfig.textColor.color }
    },
    xAxis: [{
      axisLabel: { color: echartsConfig.textColor.color },
      axisLine: { lineStyle: { color: echartsConfig.textColor.color } },
      axisTick: { lineStyle: { color: echartsConfig.textColor.color } }
    }],
    yAxis: [{
      nameTextStyle: { color: echartsConfig.textColor.color },
      axisLabel: { color: echartsConfig.textColor.color },
      splitLine: {
        lineStyle: {
          color: [echartsConfig.splitLine.color]
        }
      }
    }]
  })
  EChartsUtil.addResizeListener(lineChart.value)
}
onBeforeUnmount(() => {
  EChartsUtil.removeResizeListener(lineChart.value)
})
// endregion

currentNode.data.expose = {
  updateChartAttrs,
  updateChartText,
  updateChartArea,
  updateChartColor,
  updateSplitLineColor,
  run
}
</script>

<template>
  <div ref="lineChartRef" v-loading="isLoading" style="width: 100%;height: 100%" />
</template>

<style scoped lang="scss">

</style>
